package com.lvy.hczn.front.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lvy.hczn.front.system.mapper.SkuMapper;
import com.lvy.hczn.front.system.service.SkuService;
import com.lvy.hczn.front.system.domain.business.Sku;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

    @Autowired
    private SkuMapper skuMapper;

    @Override
    public synchronized void saveOrUpdateSku(Sku sku) {
        //数据来源组装，确定唯一
        sku.setSourceId(sku.getBarcodeId() + sku.getSiteCode() + sku.getProductSysCode());
        Sku mode = super.getById(sku.getId());
        if (mode == null) {
            LambdaQueryWrapper<Sku> queryWrapper = new LambdaQueryWrapper<>();
            if (!StrUtil.isEmpty(sku.getBarcodeSysCode())) {
                queryWrapper.eq(Sku::getBarcodeSysCode, sku.getBarcodeSysCode());
            }
            if (!StrUtil.isEmpty(sku.getProductSysCode())) {
                queryWrapper.eq(Sku::getProductSysCode, sku.getProductSysCode());
            }
            if (!StrUtil.isEmpty(sku.getSiteCode())) {
                queryWrapper.eq(Sku::getSiteCode, sku.getSiteCode());
            }
            Sku skuInfo = super.getOne(queryWrapper);
            if (skuInfo != null) {
                sku.setId(skuInfo.getId());
                super.updateById(sku);
            } else {
                super.save(sku);
            }
        } else {
            sku.setId(mode.getId());
            super.updateById(sku);
        }
    }
}